﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace zielonka.co.uk.extensions.system.collections
{
    //Description: Creates a DataTable representation of a Dictionary
    /*
       private void DataTableToDictionary1()
        {
	        Dictionary<int, string> Demo1 = new Dictionary<int, string>();

	        for (int x = 65; x <= 75; x++) {
		        Demo1.Add(x, Strings.ChrW(x));
	        }

	        dynamic dtDemo1 = Demo1.ToDatatable;
	        Console.WriteLine(dtDemo1.Rows.Count);
	        foreach (DataRow Row in dtDemo1.Rows) {
		        Console.WriteLine("{0}={1}", Row["key"], Row["value"]);
	        }

        }
    */

    public static partial class DictionaryExtensions
    {
        public static DataTable ToDatatable(IDictionary sender)
        {

            Type[] Types = sender.GetType().GetGenericArguments();
            Type keyType = Types[0];
            Type valueType = Types[1];

            DataTable dt = new DataTable { TableName = "MyDict" };

            var _with1 = dt.Columns;
            _with1.AddRange(new DataColumn[] {
		        new DataColumn("Key", System.Type.GetType(keyType.ToString())),
		        new DataColumn("Value", System.Type.GetType(valueType.ToString()))
	        });

            foreach (DictionaryEntry de in sender)
            {
                dt.Rows.Add(new object[] {
			        de.Key,
			        de.Value
		        });
            }
            return dt;
        }
    }
}
